import Vue from "vue";
import Vuex from "vuex";
import instance from "@/utils/request";

Vue.use(Vuex);

const chatModule = {
  state: {
    userList: [],
    messages: [],
    selectedUserId: null,
    ws: null,
  },
  mutations: {
    // 设置用户列表
    setUserList(state, userList) {
      state.userList = userList;
    },
    // 添加消息到消息列表
    addMessage(state, message) {
      state.messages.push(message);
    },
    // 设置选中用户的 id
    setSelectedUserId(state, userId) {
      state.selectedUserId = userId;
    },
    // 设置 WebSocket 实例
    setWebSocket(state, ws) {
      state.ws = ws;
    },
  },
  actions: {
    // 获取用户列表
    async getUserList({ commit }) {
      try {
        const response = await instance.get("/user/page?pageSize=9999");
        if (response.data.code === 0) {
          commit("setUserList", response.data.data.records);
        }
      } catch (error) {
        console.log("请求失败", error);
      }
    },
    // 发送消息
    sendMessageToServer({ state }, message) {
      if (state.ws && state.ws.readyState === WebSocket.OPEN) {
        state.ws.send(JSON.stringify(message));
      }
    },
    // 连接 WebSocket
    connectWebSocket({ commit }) {
      const user = JSON.parse(localStorage.getItem("user"));
      if (!user) {
        return;
      }
      const ws = new WebSocket("ws://websocket.1uu.pw/chat");
      ws.onopen = () => {
        console.log("连接已打开");
      };
      ws.onmessage = (event) => {
        try {
          const message = JSON.parse(event.data);
          console.log(
            `接收消息：从 ${message.sendUserName}（ID: ${message.sendUserId}） 到 ${message.receivUserName}（ID: ${message.receivUserId}），消息内容：${message.message}`
          );
          commit("addMessage", message);
        } catch (error) {
          console.error("接收到的数据不是有效的JSON格式:", event.data);
        }
      };
      ws.onclose = () => {
        console.log("连接已经关闭");
      };
      ws.onerror = (error) => {
        console.error("WebSocket 错误:", error);
        alert("WebSocket 连接失败，请刷新再试");
      };
      commit("setWebSocket", ws);
    },
  },
  getters: {
    // 获取用户列表
    getUserList: (state) => state.userList,
    // 获取消息列表
    getMessages: (state) => state.messages,
    // 获取选中用户的 id
    getSelectedUserId: (state) => state.selectedUserId,
    // 获取 WebSocket 实例
    getWebSocket: (state) => state.ws,
    // 获取选中用户的信息
    getSelectedUser: (state) => {
      return state.userList.find((user) => user.id === state.selectedUserId);
    },
  },
};

export default new Vuex.Store({
  modules: {
    chat: chatModule,
  },
});
